from typing import Dict, Any
from datetime import datetime, timedelta

# 使用字典存储任务进度
_task_progress: Dict[str, dict] = {}

def save_task_progress(task_id: str, progress_data: dict):
    """保存任务进度到内存"""
    progress_data["updated_at"] = datetime.now().isoformat()
    _task_progress[task_id] = progress_data
    
    # 清理过期的任务（1小时后过期）
    current_time = datetime.now()
    expired_tasks = []
    for tid, data in _task_progress.items():
        try:
            updated_at = datetime.fromisoformat(data["updated_at"])
            if (current_time - updated_at) > timedelta(hours=1):
                expired_tasks.append(tid)
        except (KeyError, ValueError):
            expired_tasks.append(tid)
    
    for tid in expired_tasks:
        _task_progress.pop(tid, None)

def get_task_progress(task_id: str) -> Dict[str, Any]:
    """从内存获取任务进度"""
    if task_id not in _task_progress:
        return {
            "status": "not_found",
            "message": "任务不存在或已过期"
        }
    return _task_progress[task_id] 